﻿
Imports lock_t = lock(Of locks.spinlock)

Public MustInherit Class atomicInt(Of T)
    Inherits pointer(Of T)

    Private Shared ReadOnly defaultValue As T = [default](Of T)()
    Private l As lock_t

    Public Sub New()
        Me.New(defaultValue)
    End Sub

    Public Sub New(ByVal initValue As T)
        MyBase.New(initValue)
    End Sub

    Protected MustOverride Function add(ByVal i As T, ByVal j As T) As T
    Public Function increment(ByVal i As T) As T
        Dim rtn As T = Nothing
        l.wait()
        [set](add([get](), i))
        rtn = [get]()
        l.release()
        Return rtn
    End Function

    Protected MustOverride Function _1() As T
    Public Function increment() As T
        Return increment(_1())
    End Function

    Protected MustOverride Function negative(ByVal i As T) As T
    Public Function decrement(ByVal i As T) As T
        Return increment(negative(i))
    End Function

    Public Function decrement() As T
        Return decrement(_1())
    End Function

    Public Shared Widening Operator CType(ByVal i As atomicInt(Of T)) As T
        If i Is Nothing Then
            Return defaultValue
        Else
            Return i.[get]()
        End If
    End Operator
End Class

Public Class atomicInt64
    Inherits atomicInt(Of Int64)

    Public Sub New()
        MyBase.new()
    End Sub

    Public Sub New(ByVal initValue As Int64)
        MyBase.new(initValue)
    End Sub

    Protected Overrides Function _1() As Int64
        Return 1
    End Function

    Protected Overrides Function add(ByVal i As Int64, ByVal j As Int64) As Int64
        Return i + j
    End Function

    Protected Overrides Function negative(ByVal i As Int64) As Int64
        Return -i
    End Function

    Public Overloads Shared Widening Operator CType(ByVal i As Int64) As atomicInt64
        Return New atomicInt64(i)
    End Operator
End Class

Public Class atomicUInt64
    Inherits atomicInt(Of UInt64)

    Public Sub New()
        MyBase.new()
    End Sub

    Public Sub New(ByVal initValue As UInt64)
        MyBase.new(initValue)
    End Sub

    Protected Overrides Function _1() As UInt64
        Return 1
    End Function

    Protected Overrides Function add(ByVal i As UInt64, ByVal j As UInt64) As UInt64
        Return i + j
    End Function

    Protected Overrides Function negative(ByVal i As UInt64) As UInt64
        Return -i
    End Function

    Public Overloads Shared Widening Operator CType(ByVal i As UInt64) As atomicUInt64
        Return New atomicUInt64(i)
    End Operator
End Class
